﻿#region Using Directives

using System;
using System.Web;
using System.Web.UI.WebControls;
using System.Collections.Generic;

using QuickDev.Common.Audit;
using QuickDev.Localization;

using QuickDev.Web.UI;

using QuickDev.Model;
using QuickDev.Common.Security;
using QuickDev.Common;
using QuickDev.Common.Utils;



#endregion

namespace QuickDev.Web.App.Administration
{
    public partial class Profile : AdminPage
    {
        #region Page Events

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load( object sender, EventArgs e )
        {
            try
            {
                SetProfileProperties();

                if ( !Page.IsPostBack )
                {
                    AuthWebService.AuthWebService authWebService = new AuthWebService.AuthWebService();
                    string xml = String.Empty;
                    if ( WebServices.TryParse( authWebService.GetMemberUser( WebServices.GetTicket(), Encrypts.Encrypt( Memberships.CurrentUserId.ToString() ) ), out xml ) )
                    {
                        MemberUser model = new MemberUser().NewFromXml( xml ) as MemberUser;
                        LoadMemberUser( model );
                    }

                    //If this is an existing account then we must ask for the old password as an extra 
                    //security check before changing user settings, but the user isn't required to specify a
                    //new password if they want to keep the existing one.
                    this.OldPasswordPanel.Visible = true;

                    this.rfvNewPass.Enabled = this.txtNewPass.Text.Length > 0;
                    this.rfvConfirmPassword.Enabled = this.txtNewPass.Text.Length > 0;
                    this.rfvPassword.Enabled = this.txtNewPass.Text.Length > 0;
                }
            }
            catch ( Exception ex )
            {
                Logger.Error( typeof( Profile ).Name + ".Page_Load", ex );
                Master.MessageCenter.DisplayCriticalMessage( ex.Message );
            }
        }

        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            if ( Page.IsValid )
            {
                string loginName = this.txtLoginName.Text.Trim();
                string displayName = this.txtDisplayName.Text.Trim();
                string email = this.txtEmail.Text.Trim();
                string phone = this.txtPhone.Text.Trim();
                string newPass = this.txtNewPass.Text.Trim();
                string password = this.txtPassword.Text.Trim();

                try
                {
                    String passwordHash = Security.CreatePasswordHash( password, (String)Page.Session["PWSalt"] );
                    if ( !( passwordHash.Equals( Page.Session["PWHash"] ) ) && !String.IsNullOrEmpty( password ) )
                    {
                        Master.MessageCenter.DisplayCriticalMessage( LocalizationUtility.GetStoreString( "PasswordNotMatch" ) );
                        return;
                    }

                    MemberUser model = new MemberUser();
                    model.UserId = Memberships.CurrentUserId;
                    model.LoginName = loginName;
                    model.DisplayName = displayName;
                    model.Email = email;
                    model.Phone = phone;
                    //Attention: this is wrong , but I do it on purpose.
                    model.PasswordHash = newPass;
                    model.PasswordSalt = (string)Page.Session["PWSalt"];
                    model.IPLogin = Utility.Ip;

                    AuthWebService.AuthWebService authWebService = new AuthWebService.AuthWebService();
                    string xml = String.Empty;
                    if ( WebServices.TryParse( authWebService.UpdateProfile( WebServices.GetTicket(), Encrypts.Encrypt( model.ToXml() ) ), out xml ) )
                    {
                        MemberUser model2 = new MemberUser().NewFromXml( xml ) as MemberUser;

                        if ( model2 == null )
                        {
                            Master.MessageCenter.DisplayCriticalMessage( string.Format( LocalizationUtility.GetText( "lblNotSaved" ), typeof( MemberUser ).Name ) );
                        }
                        else
                        {
                            LoadMemberUser( model2 );

                            Master.MessageCenter.DisplaySuccessMessage( string.Format( LocalizationUtility.GetText( "lblSaved" ), typeof( MemberUser ).Name ) );
                        }
                    }
                }
                catch ( System.Threading.ThreadAbortException )
                {
                    //ignore error.
                }
                catch ( Exception ex )
                {
                    Logger.Error( typeof( Profile ).Name + ".btnSave_Click", ex );
                    Master.MessageCenter.DisplayCriticalMessage( ex.Message );
                }
            }
        }

        #endregion

        #region Methods

        #region Private

        /// <summary>
        /// Sets the MemberUsers properties.
        /// </summary>
        private void SetProfileProperties()
        {
            this.rfvEmail.ErrorMessage = LocalizationUtility.GetText( "rfvEmail" );
            this.rfvPhone.ErrorMessage = LocalizationUtility.GetText( "rfvPhone" );
            this.rfvConfirmPassword.ErrorMessage = LocalizationUtility.GetText( "rfvConfirmPassword" );

            this.Title = string.Format( WebUtility.MainTitleTemplate, Master.SiteSettings.SiteName, LocalizationUtility.GetText( "titleProfile" ) );
        }

        /// <summary>
        /// LoadMemberUser( MemberUser model )
        /// </summary>
        /// <param name="model">model</param>
        private void LoadMemberUser( MemberUser model )
        {
            this.txtLoginName.Text = model.LoginName;
            this.txtDisplayName.Text = model.DisplayName;
            this.txtEmail.Text = model.Email;
            this.txtPhone.Text = model.Phone;

            Page.Session["PWSalt"] = model.PasswordSalt;
            Page.Session["PWHash"] = model.PasswordHash;
        }

        #endregion

        #endregion
    }
}
